package com.ourhours.message.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ourhours.link.annotation.Permission;
import com.ourhours.link.dto.UserInfoDto;
import com.ourhours.message.domain.Supplier;
import com.ourhours.message.dto.FieldDto;
import com.ourhours.message.dto.KeyValue;
import com.ourhours.message.enums.SupplierTypeEnum;
import com.ourhours.message.service.SupplierService;
import com.ourhours.message.common.BaseResult;
import com.ourhours.message.service.wrapper.SupplierWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 信息供应商 前端控制器
 * </p>
 *
 * @author chi.chen
 * @since 2018-03-15
 */
@Controller
@RequestMapping("/supplier")
@Slf4j
public class SupplierController extends BaseController {

    @Autowired
    SupplierService supplierService;
    @Autowired
    SupplierWrapper supplierWrapper;

    @GetMapping("/list")
    @Permission("messageSupplier")
    public String list() {
        return "supplier/list";
    }

    @PostMapping("/listAll")
    @ResponseBody
    @Permission("messageSupplierList")
    public BaseResult listAll() {
        try {
            UserInfoDto user = getLoginUser();
            Supplier supplier = new Supplier();
            supplier.setDeleted(0L);
            if (user.getVendorId() != null && user.getVendorId() != 0L) {
                supplier.setVendorId(user.getVendorId());
            }
            EntityWrapper<Supplier> wrapper = new EntityWrapper<Supplier>(supplier);
            List<Supplier> list = supplierService.selectList(wrapper);
            //初始化供应商信息
            supplierWrapper.initSupplier(user.getVendorId());
            log.info("==> SupplierController.listAll查询消息供应商列表成功,结果:{}", list);
            return BaseResult.success(list);
        } catch (Exception e) {
            log.error("==> SupplierController.listAll查询消息供应商列表失败，异常{}", e);
            return BaseResult.failure("查询失败!");
        }
    }

    @GetMapping("/edit")
    @Permission("messageSupplierEdit")
    public ModelAndView edit(Long supplierId) {
        ModelAndView modelAndView = new ModelAndView("supplier/edit");
        Supplier supplierForWrapper = new Supplier();
        Supplier supplier;
        if (supplierId != null && supplierId > 0L) {
            supplierForWrapper.setId(supplierId);
            EntityWrapper<Supplier> wrapper = new EntityWrapper<Supplier>(supplierForWrapper);
            supplier = supplierService.selectOne(wrapper);
        } else {
            supplier = new Supplier();
            supplier.setId(0L);
            supplier.setType(1);
        }
        modelAndView.addObject("supplier", supplier);
        modelAndView.addObject("fields", FieldDto.parse(supplier.getOuterExtraProperty()));
        return modelAndView;
    }

    @PostMapping("/saveOrUpdate")
    @ResponseBody
    @Permission("messageSupplierSaveOrUpdate")
    public BaseResult saveOrUpdate(Supplier entity, FieldDto fieldDto) {
        try {
            if (entity == null || entity.getId() == null) {
                log.error("==>SupplierController.update 接收到的数据为空：{}", entity);
                return BaseResult.failure("0003", "接收到的数据为空");
            }
            UserInfoDto user = getLoginUser();
            entity.setOuterExtraProperty(FieldDto.toJSONString(fieldDto));
            if (entity.getId() > 0L) {
                //修改：
                entity.setUpdateTime(new Date());
                entity.setUpdateUser(user.getUserName());
                entity.setSysVersion(entity.getSysVersion() + 1);
                supplierService.updateById(entity);
                log.info("==> SupplierController.update 更新消息供应商成功，参数:{}", entity);
                return BaseResult.success("更新消息供应商成功!", entity);
            } else {
                //添加：
                entity.setVendorId(user.getVendorId());
                entity.setSysVersion(1);
                entity.setDeleted(0L);
                entity.setCreateTime(new Date());
                entity.setCreateUser(user.getUserName());
                entity.setUpdateTime(new Date());
                entity.setUpdateUser(user.getUserName());
                supplierService.insert(entity);
                log.info("==> SupplierController.update 添加消息供应商成功，参数:{},结果:{}", entity);
                return BaseResult.success("添加消息供应商成功!", entity);
            }
        } catch (Exception e) {
            if (entity.getId() > 0L) {
                log.error("==>SupplierController.update 保存消息供应商异常：{}", e);
                return BaseResult.failure("0002", "更新消息供应商异常");
            } else {
                log.error("==>SupplierController.update 添加消息供应商异常：{}", e);
                return BaseResult.failure("0001", "添加消息供应商异常");
            }
        }
    }


    @PostMapping("/getSupplierTypeByMessageType")
    @ResponseBody
    public BaseResult getSupplierTypeByMessageType(int type) {
        List<KeyValue> data = new ArrayList<KeyValue>();
        try {
            SupplierTypeEnum[] supplierTypeEnums = SupplierTypeEnum.getSupplierTypeEnumValuesByMessageTypeEnum(type);
            for (int i = 0; i < supplierTypeEnums.length; i++) {
                KeyValue keyValue = new KeyValue();
                keyValue.setKey(supplierTypeEnums[i].getCode() + "");
                keyValue.setValue(supplierTypeEnums[i].getContent());
                data.add(keyValue);
            }
            return BaseResult.success(data);
        } catch (Exception e) {
            return BaseResult.failure(e.getMessage());
        }
    }

    @PostMapping("/changeStatus")
    @ResponseBody
    public BaseResult changeStatus(Long id, Integer status) {
        try {
            Supplier entity = new Supplier();
            entity.setStatus(status);
            entity.setId(id);
            supplierService.updateById(entity);
            Supplier selectSupplier =  supplierService.selectById(id);
            if (status == 1) {
                supplierWrapper.addSupplierCache(selectSupplier);
            } else if (status == 0) {
                supplierWrapper.delSupplierCache(selectSupplier);
            }
            log.info("==> SupplierController.changeStatus 修改供应商状态成功.参数，{},{}", id, status);
            return BaseResult.success();
        } catch (Exception e) {
            log.error("==> SupplierController.changeStatus 修改供应商状态失败.参数，{},{}.异常{}", id, status, e);
            return BaseResult.failure("操作失败:" + e.getMessage());
        }
    }
}

